import { ErrorType } from '../errors';
import { Controller } from 'egg';

export default function validateInput(
  rules: any,
  errorType: ErrorType,
): MethodDecorator {
  return function (_, __, descriptor: PropertyDescriptor) {
    const orginalMethod = descriptor.value;
    descriptor.value = function (this: Controller, ...args: any) {
      const { ctx, app } = this;
      const errors = app.validator.validate(rules, ctx.request.body);
      if (errors) {
        return ctx.helper.error({ ctx, errorType, error: errors });
      }
      return orginalMethod.apply(this, args);
    };
  };
}
